<template>
	<view class="page-container">

		<!-- 营业执照上传 -->
		<view class="upload-section">
			<view class="section-title">营业执照</view>
			<view class="upload-card" @click="handleUploadLicense">
				<image v-if="licenseImage" :src="licenseImage" class="license-image" mode="aspectFit">
				</image>
				<view v-else class="upload-placeholder">
					<uni-icons type="plusempty" size="40" color="#999"></uni-icons>
					<text class="upload-text">上传营业执照</text>
					<text class="format-tip">照片格式：jpg/png</text>
				</view>
			</view>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<view class="notice-text">以下信息为系统自动识别，如不正确请修改</view>

			<view class="form-item">
				<text class="form-label">企业名称</text>
				<input v-model="formData.enterpriseName" placeholder="请输入企业名称" placeholder-class="placeholder"
					class="form-input" />
				<text class="error-msg" v-if="errors.enterpriseName">{{ errors.enterpriseName }}</text>
			</view>

			<view class="form-item">
				<text class="form-label">信用代码</text>
				<input v-model="formData.creditCode" placeholder="请输入18位信用代码" placeholder-class="placeholder"
					class="form-input" maxlength="18" @input="formatCreditCode" />
				<text class="error-msg" v-if="errors.creditCode">{{ errors.creditCode }}</text>
			</view>

			<view class="form-item">
				<text class="form-label">法定代表人</text>
				<input v-model="formData.legalRepresentative" placeholder="请输入法定代表人姓名" placeholder-class="placeholder"
					class="form-input" maxlength="20" />
				<text class="error-msg" v-if="errors.legalRepresentative">{{ errors.legalRepresentative }}</text>
			</view>

			<view class="form-item">
				<text class="form-label">营业期限起</text>
				<picker mode="date" fields="day" @change="(e) => handleDateChange('startDate', e)">
					<view class="picker-content">
						{{ formData.businessStartDate || '请选择日期' }}
					</view>
				</picker>
				<text class="error-msg" v-if="errors.businessStartDate">{{ errors.businessStartDate }}</text>
			</view>

			<view class="form-item">
				<text class="form-label">营业期限止</text>
				<picker mode="date" fields="day" @change="(e) => handleDateChange('endDate', e)">
					<view class="picker-content">
						{{ formData.endDate || '请选择日期' }}
					</view>
				</picker>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn" @click="handleSubmit">
			<text>确认提交</text>
		</view>

		<!-- OCR提示 -->


		<view class="divider"></view>




	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import "@/config/request.js";
	import {
		http
	} from "@/config/request.js";
	import {
		useuser
	} from "@/stores/user.js";
	import {
		useTokenStore
	} from "@/stores/jwt.js";
	const user = useuser();
	const token = useTokenStore().jwt;
	// 表单数据
	const formData = ref({})


	// 营业执照图片
	const licenseImage = ref('')

	// 错误信息
	const errors = reactive({
		enterpriseName: '',
		creditCode: '',
		legalRepresentative: '',
		businessStartDate: ''
	})


	// 上传营业执照
	const handleUploadLicense = () => {
		wx.chooseImage({
			count: 1,
			success: (res) => {
				licenseImage.value = res.tempFilePaths[0]

				// 这里可以调用OCR识别接口，将图片上传到服务器进行识别
				uni.uploadFile({
					url: 'http://localhost:9988/licenseAuthentication/update', //仅为示例，非真实的接口地址
					filePath: licenseImage.value,
					name: 'file',
					header: {
						'Authorization': `${token}` // 这里加入令牌（token）
					},
					success: (uploadFileRes) => {
						console.log("上传成功", uploadFileRes.data);
						const res = JSON.parse(uploadFileRes.data);
						console.log("res", res);
						if (res.code === 20031) {
							formData.value = res.shuju
							licenseImage.value = res.shuju.licenseImagePath

							uni.showToast({
								title: '识别成功',
								icon: 'success',
							});
						} else {
							uni.showToast({
								title: '识别失败',
								icon: 'none',
								duration: 2000,
							});
						}
					}
				});
			}
		})
	}

	// 格式化信用代码（自动转大写）
	const formatCreditCode = () => {
		formData.value.creditCode = formData.value.creditCode.toUpperCase()
	}

	// 日期选择处理
	const handleDateChange = (field, e) => {
		formData.value[field] = e.detail.value
	}

	// 验证信用代码
	const validateCreditCode = () => {
		const code = formData.value.creditCode
		const invalidChars = ['I', 'O', 'Z', 'S', 'V']

		if (!code) {
			errors.creditCode = '请输入信用代码'
			return false
		}

		if (code.length !== 18) {
			errors.creditCode = '信用代码必须为18位'
			return false
		}

		for (let char of invalidChars) {
			if (code.includes(char)) {
				errors.creditCode = `不能包含字母${char}`
				return false
			}
		}

		errors.creditCode = ''
		return true
	}

	// 验证法定代表人
	const validateLegalPerson = () => {
		const name = formData.value.legalRepresentative

		if (!name) {
			errors.legalRepresentative = '请输入法定代表人'
			return false
		}

		if (!/^[\u4e00-\u9fa5]{1,20}$/.test(name)) {
			errors.legalRepresentative = '请输入1-20位汉字'
			return false
		}

		errors.legalRepresentative = ''
		return true
	}
	// 验证所有必填字段
	const validateForm = () => {
		let valid = true;

		// 验证企业名称
		if (!formData.value.enterpriseName) {
			errors.enterpriseName = '请输入企业名称';
			valid = false;
		} else {
			errors.enterpriseName = '';
		}

		// 验证信用代码
		if (!validateCreditCode()) {
			valid = false;
		}

		// 验证法定代表人
		if (!validateLegalPerson()) {
			valid = false;
		}

		// 验证营业期限起始日期
		if (!formData.value.businessStartDate) {
			errors.businessStartDate = '请选择营业期限起始日期';
			valid = false;
		} else {
			errors.businessStartDate = '';
		}
		return valid;
	}


	const tijiao = async () => {
		console.log(user.user.id)
		console.log(formData.value);
		formData.value.eid = user.user.id
		formData.value.auditStatus = 0
		const res = await http({
			url: '/licenseAuthentication/add',
			method: 'POST',
			data: formData.value
		})
		console.log(res);
		if (res.code === 20011) {
			uni.showToast({
				title: '提交成功',
				icon: 'success',
				duration: 2000,
				success: () => {
					// 提交成功后返回上一页
					wx.navigateBack({
						delta: 1 // 返回上一页，delta可以设置返回几层页面
					});
				}
			});
		} else {
			uni.showToast({
				title: '提交失败',
				icon: 'none',
				duration: 2000,
			});
		}
	}
	const handleSubmit = () => {
		console.log("表单信息" + formData.value);
		if (validateForm()) {
			tijiao();
		} else {
			uni.showToast({
				title: '请完善表单信息',
				icon: 'none',
				duration: 2000
			});
		}
	}
</script>

<style lang="scss">
	.page-container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.time-display {
		font-size: 36rpx;
		color: #333;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.upload-section {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
		}

		.upload-card {
			height: 300rpx;
			border: 2rpx dashed #ddd;
			border-radius: 12rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			overflow: hidden;

			.license-image {
				width: 100%;
				height: 100%;
			}

			.upload-placeholder {
				display: flex;
				flex-direction: column;
				align-items: center;

				.upload-text {
					font-size: 28rpx;
					color: #666;
					margin-top: 15rpx;
				}

				.format-tip {
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
				}
			}
		}
	}

	.form-section {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;

		.notice-text {
			font-size: 26rpx;
			color: #999;
			margin-bottom: 30rpx;
		}

		.form-item {
			margin-bottom: 30rpx;

			.form-label {
				display: block;
				font-size: 28rpx;
				color: #666;
				margin-bottom: 10rpx;
			}

			.form-input {
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 20rpx;
				background-color: #f9f9f9;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #333;
			}

			.picker-content {
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 20rpx;
				background-color: #f9f9f9;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #999;
			}

			.error-msg {
				font-size: 24rpx;
				color: #ff4d4f;
				margin-top: 5rpx;
			}
		}
	}

	.submit-btn {
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		background-color: #1890ff;
		color: #fff;
		font-size: 32rpx;
		border-radius: 45rpx;
		margin: 40rpx 0;
	}

	.ocr-tip {
		font-size: 26rpx;
		color: #999;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.divider {
		height: 1rpx;
		background-color: #eee;
		margin: 30rpx 0;
	}

	.validation-tips {
		background-color: #fff8e6;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;

		.tip-item {
			font-size: 26rpx;
			color: #fa8c16;
			margin-bottom: 10rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	.format-requirements {
		background-color: #f6f6f6;
		border-radius: 8rpx;
		padding: 20rpx;

		.requirement-title {
			font-size: 26rpx;
			font-weight: bold;
			color: #666;
			margin-bottom: 10rpx;
		}

		.requirement-item {
			font-size: 24rpx;
			color: #999;
			margin-bottom: 8rpx;
			padding-left: 20rpx;
			position: relative;

			&::before {
				content: "•";
				position: absolute;
				left: 0;
			}
		}
	}

	.placeholder {
		color: #ccc;
		font-size: 28rpx;
	}
</style>